<template>
  <div class="home-page">
    <!-- 顶部导航 -->
    <div class="header flex justify-between items-center p-4 bg-white shadow-sm rounded-lg mb-4">
      <div class="flex items-center">
        <img :src="logo" alt="LOGO" class="w-10 h-10 rounded-full mr-3" />
        <div class="text-xl font-bold">{{ companyObject.company?.name || '' }}</div>
        <!-- <el-tag size="small" class="ml-3" type="primary">渠道商: 个人</el-tag>
        <el-tag size="small" class="ml-2" type="warning">已入驻天猫认证</el-tag> -->
      </div>

    </div>

    <div class="flex gap-4" id="print">
      <!-- 左侧主要内容 -->
      <div class="flex-1">
        <!-- 统计卡片 -->
        <div class="grid grid-cols-4 gap-4 mb-4">
          <!-- 今日订单 -->
          <el-card shadow="hover" class="text-center">
            <div class="text-lg font-semibold mb-3">今日订单</div>
            <div class="grid grid-cols-2 gap-2">
              <div>
                <div class="text-gray-600 text-sm">今日订单数</div>
                <div class="text-xl font-bold text-gray-800 mt-1">{{ orderSummary.todayOrderCount }}</div>
              </div>
              <div>
                <div class="text-gray-600 text-sm">今日销售额</div>
                <div class="text-xl font-bold text-green-600 mt-1">¥{{ orderSummary.todaySalesAmount }}</div>
              </div>
            </div>
          </el-card>

          <!-- 本月订单 -->
          <el-card shadow="hover" class="text-center">
            <div class="text-lg font-semibold mb-3">本月订单</div>
            <div class="grid grid-cols-2 gap-2">
              <div>
                <div class="text-gray-600 text-sm">本月订单数</div>
                <div class="text-xl font-bold text-gray-800 mt-1">{{ orderSummary.monthOrderCount }}</div>
              </div>
              <div>
                <div class="text-gray-600 text-sm">本月销售额</div>
                <div class="text-xl font-bold text-red-600 mt-1">¥{{ orderSummary.monthSalesAmount }}</div>
              </div>
            </div>
          </el-card>

          <!-- 客户总数 -->
          <el-card shadow="hover" class="text-center">
            <div class="text-gray-500">客户总数</div>
            <div class="text-2xl font-bold mt-2">{{ orderSummary.customerTotal }}</div>
            <!-- <div class="text-green-500 text-sm mt-1">↑ 17%</div> -->
          </el-card>

          <!-- 产品总数 -->
          <el-card shadow="hover" class="text-center">
            <div class="text-gray-500">产品总数</div>
            <div class="text-2xl font-bold mt-2">{{ orderSummary.productTotal }}</div>
            <!-- <div class="text-red-500 text-sm mt-1">↓ 10%</div> -->
          </el-card>
        </div>
        <!-- 最近订单表 -->
        <el-card shadow="hover">
          <div class="flex justify-between items-center mb-4">
            <div class="text-lg font-semibold">最近订单</div>
            <el-link type="primary" class="text-sm" @click="goToOrderList">更多</el-link>
          </div>
          <el-table :data="orderSummary.recentOrders" stripe border style="width: 100%">
            <el-table-column prop="orderNo" label="订单号" width="180" />
            <el-table-column prop="customerName" label="客户名称" />
           
            <el-table-column prop="orderType.info" label="订单类型" />
             <el-table-column prop="isCancel" label="订单状态" >
               <template #default="scope">
                   <dict-tag :options="is_cancel" :value="scope.row.isCancel?.code" />
               </template>
             </el-table-column>
            <el-table-column prop="amount" label="金额" />

            <el-table-column prop="creatorName" label="开单人" />

            <el-table-column prop="createTime" label="日期" />
          </el-table>

          <div class="flex justify-end mt-4">
            <!-- <el-pagination layout="prev, pager, next" :total="200" :page-size="10" /> -->
          </div>
        </el-card>
      </div>

      <!-- 右侧快捷开单 -->
      <div class="w-[280px]">
        <el-card shadow="hover">
          <div class="text-lg font-semibold mb-4">快捷开单</div>
          <div class="grid grid-cols-3 gap-4">
            <div v-for="(item,index) in quickList" :key="item.name" class="text-center cursor-pointer hover:opacity-80">
              <div class="rounded-full p-3 inline-block bg-gray-100" @click="quickOrderClick(item)">
                <img :src="item.icon" alt="icon" class="w-6 h-6 mx-auto" />
              </div>
              <div class="text-sm mt-1">{{ item.name }}</div>
            </div>
          </div>
        </el-card>

        <!-- 二维码 -->
        <el-card class="mt-4 text-center">
          <img :src="qrcoder" alt="二维码" class="w-32 h-32 mx-auto mb-2" />
          <div class="text-gray-500 text-sm">客服微信</div>
          <div class="text-gray-700 text-sm mt-1">13058857770</div>
        </el-card>
      </div>
    </div>


    <!-- 客户选择弹窗 -->
    <el-dialog v-model="showCustomerDialog" title="选择客户 / 供应商" width="700px">
      <el-tabs v-model="activeTab" @tab-change="handleCustomerTabChange">
        <el-tab-pane label="客户" name="customer">
          <el-table :data="customerList" style="width: 100%" @row-click="handleCustomerRowClick">
            <el-table-column prop="customerName" label="客户名称" />
            <el-table-column prop="contactPerson" label="联系人" />
            <el-table-column prop="phone" label="联系电话" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="供应商" name="supplier">
          <el-table :data="supplierList" style="width: 100%" @row-click="handleSupplierRowClick">
            <el-table-column prop="supplierName" label="供应商名称" />
            <el-table-column prop="contactPerson" label="联系人" />
            <el-table-column prop="phone" label="联系电话" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 打印预览弹窗 -->
    <el-dialog v-model="showPrintPreview" title="打印预览" width="1000px" append-to-body destroy-on-close>
      <div id="printTemplate" v-html="printTemplate" class="print-template">
      </div>
      <!-- <template #footer>
        <el-button @click="showPrintPreview = false">关闭</el-button>
      </template> -->
    </el-dialog>


    <!-- 收货地址弹窗 -->
    <el-dialog v-model="showAddressDialog" title="收货地址" width="500px">
      <!-- 地址列表 -->
      <el-scrollbar height="300px">
        <el-card v-for="(item, index) in addressList" :key="index" class="mb-3 cursor-pointer hover:bg-gray-50"
          @click="selectAddress(item)">
          <div class="flex justify-between">
            <div>
              <div class="font-semibold">{{ item.name }}</div>
              <div class="text-gray-600 text-sm">{{ item.phone }}</div>
            </div>
            <div class="text-gray-700 text-sm">{{ assembleAddress(item) }}</div>
          </div>
        </el-card>
      </el-scrollbar>

      <!-- 新增按钮 -->
      <template #footer>
        <el-button type="primary" @click="openAddAddress">新增地址</el-button>
        <el-button @click="showAddressDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增地址弹窗 -->
    <el-dialog v-model="showAddDialog" title="新增地址" width="500px">
      <el-form ref="newAddressFormRef" :model="newAddress" :rules="newAddressRules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="newAddress.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="序号" prop="sort">
          <el-input-number v-model="newAddress.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="newAddress.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="省市区" prop="province">
          <el-cascader :options="regionData" @change="handleNewAddressRegionChange" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="newAddress.address" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">保存</el-button>
      </template>
    </el-dialog>


    <!-- 强制补全公司信息弹窗 -->
    <el-dialog v-model="forceCompanyDialogVisible" title="去完善" width="700px" append-to-body destroy-on-close
      :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <el-form ref="completeCompanyFormRef" :model="completeCompanyForm" :rules="completeCompanyRules"
        label-width="140px">
        <el-alert title="为确保正常开单，请先完善公司信息" type="warning" show-icon class="mb-3" />
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="主体全称" prop="name">
              <el-input v-model="completeCompanyForm.name" placeholder="请输入主体全称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="主体简称" prop="shortName">
              <el-input v-model="completeCompanyForm.shortName" placeholder="请输入主体简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人1" prop="contactPerson1">
              <el-input v-model="completeCompanyForm.contactPerson1" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式1" prop="contact1">
              <el-input v-model="completeCompanyForm.contact1" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人2" prop="contactPerson2">
              <el-input v-model="completeCompanyForm.contactPerson2" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式2" prop="contact2">
              <el-input v-model="completeCompanyForm.contact2" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="地址信息" prop="province">
              <el-row :gutter="10">
                <el-cascader :options="regionData" @change="handleAddressChange">
                </el-cascader>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input v-model="completeCompanyForm.detailAddress" placeholder="请输入详细地址" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="签名" prop="signature">
              <el-input v-model="completeCompanyForm.signature" placeholder="请输入签名" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" :loading="completingCompany" @click="submitCompleteCompany">提 交</el-button>
      </template>
    </el-dialog>

    <!-- 产品选择弹窗 -->
    <el-dialog v-model="showProductDialog" title="选择产品" width="900px">
      <!-- 条件筛选区 -->
      <div class="filter-bar">
        <el-select v-model="filters.categoryId" placeholder="选择分类" clearable style="width: 150px;margin-right: 10px;">
          <el-option label="全部分类" :value="undefined" />
          <el-option v-for="item in categoryList" :key="item.id" :label="item.categoryName" :value="item.id" />
        </el-select>

        <el-select v-model="filters.groupId" placeholder="选择分组" clearable style="width: 150px;margin-right: 10px;">
          <el-option label="全部分组" :value="''" />
          <el-option v-for="item in groupList" :key="item.id" :label="item.groupName" :value="item.id" />
        </el-select>

        <el-input v-model="filters.keyword" placeholder="搜索产品名称" prefix-icon="el-icon-search"
          style="width: 200px;margin-right: 10px;" />

        <el-button type="primary" @click="searchProducts">搜索</el-button>
      </div>

      <!-- 产品表格 -->
      <el-table ref="productTableRef" :data="filteredProducts" :row-key="getProductRowKey" :reserve-selection="true"
        border height="400px" @selection-change="handleSelectionChange" style="margin-top: 10px">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="name" label="产品名称" />
        <el-table-column prop="spec" label="规格" width="80" />
        <el-table-column prop="productCategoryInfo.categoryName" label="分类" />
        <el-table-column prop="productGroupInfo.groupName" label="分组" />
        <el-table-column prop="unitPrice" label="单价(¥)" />
        <el-table-column prop="unit" label="单位" width="80" />

      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 10px; display: flex; justify-content: flex-end;">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="productTotal"
          v-model:current-page="productPageNum" v-model:page-size="productPageSize"
          @current-change="handleProductPageChange" @size-change="handleProductSizeChange" :page-sizes="[10, 20, 50]" />
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <el-button @click="showProductDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmSelection">确认选择</el-button>
      </template>
    </el-dialog>

    <!-- 模板选择弹窗 -->
    <el-dialog v-model="showTemplateDialog" title="选择打印模板" width="800px">
      <!-- 模板卡片列表 -->
      <div class="template-list">
        <el-row :gutter="20">
          <el-col v-for="item in templateList" :key="item.id" :span="8">
            <div class="template-card" :class="{ active: selectedTemplate?.id === item.id }"
              @click="selectTemplate(item)">
              <ImagePreview :src="item.templateInfo.imageUrl" class="template-img" alt="模板预览" />
              <!-- <el-image :src="item.templateInfo.imageUrl" class="template-img" alt="模板预览" /> -->
              <div class="template-info">
                <div class="template-name">{{ item.templateInfo.name }}</div>
                <div class="template-desc">{{ item.templateInfo.templateName }}</div>
                <div class="template-desc">{{ item.templateInfo.printType.info }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <el-button @click="showTemplateDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmTemplate">确认选择</el-button>
      </template>
    </el-dialog>


    <!-- 发货单弹窗 -->
    <el-dialog v-model="showDialog" :title="form.orderTypeName || ''" width="900px" class="delivery-dialog">
      <el-form :model="form" label-width="120px" class="delivery-form">
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择客户" @click="showCustomerDialogClick">
              <el-input v-model="form.customer" placeholder="点击选择客户" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择发货地址" @click="openAddressDialog">
              <el-input v-model="form.address" placeholder="点击选择地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择模板">
              <el-button type="primary" @click="showTemplateDialogClick">{{ selectedTemplate?.templateInfo?.templateName
                || '选择打印模板' }}</el-button>
              <!-- <el-select v-model="form.template" placeholder="请选择模板">
                <el-option label="默认模板" value="default" />
                <el-option label="简洁模板" value="simple" />
                <el-option label="详细模板" value="detailed" />
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择商品">
              <!-- <el-input  :placeholder="`已选${selectedProducts.length}件商品`" /> -->
              <el-button type="primary" @click="showProductDialogClick">{{ selectedProducts.length ?
                `已选${selectedProducts.length}件商品` : '选择商品' }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 运费设置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="运费">
              <el-input-number v-if="form.showFreight" v-model="form.freight" :min="0" :precision="2"
                :disabled="!form.showFreight" />
              <el-switch v-model="form.showFreight" active-text="" inactive-text="" style="margin-left: 12px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 发货备注 -->
        <el-form-item label="发货备注">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注（可选）" maxlength="500" show-word-limit />
        </el-form-item>

        <!-- 商品信息 -->
        <el-card shadow="never" class="sign-card">
          <template #header>
            <div class="card-header">商品信息</div>
          </template>
          <!-- 已选产品表格 -->
          <el-table :data="selectedProducts" border style="margin-top: 15px">
            <el-table-column prop="name" label="产品名称" />
            <el-table-column prop="spec" label="规格" />

            <el-table-column prop="price" label="单价(¥)">
              <template #default="{ row }">
                <el-input v-model="row.price" :min="0" size="small" :disabled="true"/>
              </template>
            </el-table-column>
            <el-table-column label="数量">
              <template #default="{ row }">
                <el-input-number v-model="row.quantity" :min="1" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="金额(¥)">
              <template #default="{ row }">
                {{ (row.price * (row.quantity || 1)).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ $index }">
                <el-button type="danger" size="small" @click="removeProduct($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 订单确认信息 -->
        <el-card shadow="never" class="info-card">
          <template #header>
            <div class="card-header">订单信息确认</div>
          </template>

          <el-row :gutter="20">
            <el-col :span="12">
              <p><strong>{{ selectedParty.type === 'CUSTOMER' ? '客户' : '供应商' }}：</strong> {{ form.customer || '-' }}</p>
              <p><strong>联系人：</strong> {{ selectedParty.contactPerson || '-' }}</p>
              <p><strong>联系电话：</strong> {{ selectedParty.phone || '-' }}</p>
              <p><strong>收货地址：</strong> {{ selectedParty.address || '-' }}</p>
              <p><strong>备注：</strong> {{ form.remark || '-' }}</p>
            </el-col>
            <el-col :span="12">
              <p><strong>发货人：</strong> {{ selectedAddressParty.name || '-' }}</p>
              <p><strong>发货地址：</strong> {{ selectedAddressParty.address || '-' }}</p>
              <p><strong>联系电话：</strong> {{ selectedAddressParty.phone || '-' }}</p>
              <p><strong>发货日期：</strong> {{ today }}</p>
              <p><strong>商品总数：</strong> {{selectedProducts.reduce((total, item) => total + (item.quantity || 1), 0)}}
              </p>
              <p v-if="form.showFreight"><strong>运费：</strong> ¥{{ (form.freight || 0).toFixed(2) }}</p>
              <p><strong>总金额：</strong> ¥{{ form.amount.toFixed(2) }}</p>
            </el-col>
          </el-row>
        </el-card>
      </el-form>

      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="info" @click="openPrintPreview">预览</el-button>
        <el-button type="warning" @click="saveOrder">保存</el-button>
        <el-button type="primary" @click="saveAndPrint">保存并打印</el-button>
      </template>
    </el-dialog>

    <!-- 打印机选择弹窗 -->
    <el-dialog title="选择打印机" v-model="printDialogVisible" width="30%">
      <el-form-item label="打印机" label-position="right">
        <el-select v-model="selectedPrinter">
          <el-option v-for="item in printers" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="份数" label-position="right">
        <el-input-number v-model="printCount" :min="1" size="small" />
      </el-form-item>
      <template #footer>
        <el-button @click="printDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPrinter">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, nextTick, onMounted, reactive } from 'vue'
import { regionData, codeToText } from 'element-china-area-data';
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
// 客户列表
import { myCustomerList } from '@/api/customer';
// 供应商列表
import { listMySupplier } from '@/api/supplier';
// 模板市场列表
import { myCollectTemplateList } from '@/api/templateMarket'
// 新增订单
import { myAddOrder, getOrderNo ,delMyAddress } from '@/api/order'
//商品列表
import { listMyProduct } from '@/api/product'
// 分类列表
import { listMyProductCategory } from '@/api/productCategory'
// 分组列表
import { listProductGroup } from '@/api/productGroup'

// 首页面板接口
import { getOrderSummary } from '@/api/order'

import { getCompanyDetail,checkCompany,completeCompany } from '@/api/company';

import { myListAddress, addAddress } from '@/api/address';



import logo from '@/assets/icons/index/icon1.png'
import qrcoder from '@/assets/images/qrcode.png'

// 快捷开单图标
import icon1 from '@/assets/icons/index/icon1.png'
import icon2 from '@/assets/icons/index/icon2.png'
import icon3 from '@/assets/icons/index/icon3.png'
import icon4 from '@/assets/icons/index/icon4.png'
import icon5 from '@/assets/icons/index/icon5.png'
import icon6 from '@/assets/icons/index/icon6.png'
import icon7 from '@/assets/icons/index/icon7.png'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { is_cancel } = toRefs<any>(proxy?.useDict('is_cancel'));

// 跳转到订单列表页
const router = useRouter()
const goToOrderList = () => {
  router.push('/order/index')
}

const activeTab = ref('customer')
// 客户选择弹窗切换标签
const handleCustomerTabChange = (tab) => {
  activeTab.value = tab
  console.log('切换到标签：', tab)
  if (tab === 'customer') {
    myCustomerList().then(res => {
      customerList.value = res.rows || []
    })
  } else if (tab === 'supplier') {
    listMySupplier().then(res => {
      supplierList.value = res.rows || []
    })
  }
}

// 行点击选择客户
const handleCustomerRowClick = (row) => {
  selectedParty.value = {
    id: row.id,
    type: 'CUSTOMER',
    contactPerson: row.contactPerson,
    name: row.customerName,
    phone: row.phone,
    address: assembleAddress(row)
  }
  form.value.customer = selectedParty.value.name
  form.value.customerId = selectedParty.value.id
  showCustomerDialog.value = false
}

// 行点击选择供应商
const handleSupplierRowClick = (row) => {
  selectedParty.value = {
    id: row.id,
    type: 'SUPPLIER',
    contactPerson: row.contactPerson,
    name: row.supplierName,
    phone: row.phone,
    address: assembleAddress(row)
  }
  form.value.customer = selectedParty.value.name
  form.value.address = selectedParty.value.address
  showCustomerDialog.value = false
}

const showDialog = ref(false)
watch(showDialog, (val, oldVal) => {
  if (oldVal && !val) {
    resetOrderForm()
  }
})
// 客户选择弹窗
const showCustomerDialog = ref(false)

// 控制弹窗开关
const showAddressDialog = ref(false)
// 地址列表
const addressList = ref([])
// 新增地址表单
const newAddress = ref({ name: '', sort: 1, phone: '', province: '', city: '', area: '', address: '' })
// 新增地址表单引用与校验规则
const newAddressFormRef = ref<FormInstance>()

const showAddDialog = ref(false);

const newAddressRules: FormRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  sort: [{ type: 'number', required: false, trigger: 'change' }],
  province: [{ required: true, message: '请选择省市区', trigger: 'change' }],
  city: [{ required: true, message: '请选择省市区', trigger: 'change' }],
  area: [{ required: true, message: '请选择省市区', trigger: 'change' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}
// 处理新增地址的省市区选择
const handleNewAddressRegionChange = (selected: string[]) => {
  if (selected && selected.length === 3) {
    newAddress.value.province = codeToText[selected[0]]
    newAddress.value.city = codeToText[selected[1]]
    newAddress.value.area = codeToText[selected[2]]
  } else {
    newAddress.value.province = ''
    newAddress.value.city = ''
    newAddress.value.area = ''
  }
}

// 强制补全公司信息 - 表单与弹窗状态
const forceCompanyDialogVisible = ref(false)
const completingCompany = ref(false)
const completeCompanyFormRef = ref<FormInstance>()
const completeCompanyForm = reactive({
  companyCode: '',
  subjectType: 'ENTERPRISE',
  name: '',
  shortName: '',
  signature: '',
  contactPerson1: '',
  contact1: '',
  contactPerson2: '',
  contact2: '',
  province: '',
  city: '',
  district: '',
  detailAddress: ''
})
const completeCompanyRules: FormRules = {
  companyCode: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }],
  subjectType: [{ required: true, message: '请选择主体类型', trigger: 'change' }],
  name: [{ required: true, message: '请输入主体全称', trigger: 'blur' }],
  shortName: [{ required: true, message: '请输入主体简称', trigger: 'blur' }],
  contactPerson1: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contact1: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  province: [{ required: true, message: '请输入省', trigger: 'blur' }],
  city: [{ required: true, message: '请输入市', trigger: 'blur' }],
  district: [{ required: true, message: '请输入区/县', trigger: 'blur' }],
  detailAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}
const prefillCompleteCompanyForm = (company: any) => {
  if (!company) return
  completeCompanyForm.companyCode = company.companyCode || completeCompanyForm.companyCode
  completeCompanyForm.subjectType = company.subjectType?.code || company.subjectType || completeCompanyForm.subjectType
  completeCompanyForm.name = company.name || ''
  completeCompanyForm.shortName = company.shortName || ''
  completeCompanyForm.signature = company.signature || ''
  completeCompanyForm.contactPerson1 = company.contactPerson1 || ''
  completeCompanyForm.contact1 = company.contact1 || ''
  completeCompanyForm.contactPerson2 = company.contactPerson2 || ''
  completeCompanyForm.contact2 = company.contact2 || ''
  completeCompanyForm.province = company.province || ''
  completeCompanyForm.city = company.city || ''
  completeCompanyForm.district = company.district || ''
  completeCompanyForm.detailAddress = company.detailAddress || ''
}
const submitCompleteCompany = async () => {
  if (!completeCompanyFormRef.value) return
  try {
    await completeCompanyFormRef.value.validate()
    completingCompany.value = true
    await completeCompany(completeCompanyForm)
    ElMessage.success('公司信息已补全')
    forceCompanyDialogVisible.value = false
    // 刷新公司信息
    const detail = await getCompanyDetail()
    companyObject.value = detail.data
  } catch (e) {
    ElMessage.error('提交失败，请检查表单或稍后再试')
  } finally {
    completingCompany.value = false
  }
}

// 打开新增地址弹窗
const openAddAddress = () => {
  newAddress.value = { name: '', sort: 1, phone: '', province: '', city: '', area: '', address: '' }
  showAddDialog.value = true
}

// 保存新增地址
const saveAddress = async () => {
  if (!newAddressFormRef.value) return
  try {
    await newAddressFormRef.value.validate()
    await addAddress(newAddress.value)
    ElMessage.success('新增地址成功')
    showAddDialog.value = false
    // 刷新地址列表
    const res = await myListAddress()
    addressList.value = res.rows || []
  } catch (e) {
    ElMessage.error('保存失败，请检查表单或稍后重试')
  }
}

const selectedAddressParty = ref({});


// 处理地址级联选择器变化
const handleAddressChange = (selectedOptions: string[]) => {
  console.log('级联选择器变化：', selectedOptions)
  if (selectedOptions.length === 3) {
    completeCompanyForm.province = codeToText[selectedOptions[0]]
    completeCompanyForm.city = codeToText[selectedOptions[1]]
    completeCompanyForm.district = codeToText[selectedOptions[2]]
  }
}

// 选择地址
const selectAddress = (item) => {
  console.log('选择的地址：', item)
  selectedAddressParty.value = item
  showAddressDialog.value = false
  form.value.address = item.province + item.city + item.address
  form.value.addressId = item.id
}

// 商品选择弹窗
const showProductDialog = ref(false)
const selectedProducts = ref([])
// 跨弹窗持久化已选商品（用于恢复勾选）
const persistedSelectedProducts = ref<any[]>([])

// 选中商品或其价格/数量变更时，联动计算总金额（仅根据产品）
watch(selectedProducts, () => {
  const amount = calcAmount()
  form.value.amount = amount
  form.value.actualAmount = amount - (form.value.discountAmount || 0)
}, { deep: true })

const filters = ref({
  categoryId: undefined,
  groupId: undefined,
  keyword: ''
})
// 分类/分组变化时重置到第1页并拉取列表，保持与选择回显逻辑一致
watch(() => filters.value.categoryId, () => {
  productPageNum.value = 1
  getProductList()
})
watch(() => filters.value.groupId, () => {
  productPageNum.value = 1
  getProductList()
})

// 替换静态列表为后端数据
const categoryList = ref<any[]>([])
const groupList = ref<any[]>([])

// 拉取分类列表
const getCategoryList = async () => {
  try {
    const res: any = await listMyProductCategory()
    categoryList.value = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : [])
  } catch (e) {
    categoryList.value = []
  }
}
// 拉取分组列表
const getProductGroupList = async () => {
  try {
    const res: any = await listProductGroup()
    groupList.value = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : [])
  } catch (e) {
    groupList.value = []
  }
}

// 产品列表（后端）
const productList = ref<any[]>([])
// 产品分页
const productPageNum = ref(1)
const productPageSize = ref(10)
const productTotal = ref(0)
// 恢复过程标志，避免程序化勾选触发持久集合覆盖
const restoringSelection = ref(false)
// 表格引用（用于恢复勾选）
const productTableRef = ref()
// 统一产品行的主键获取（兼容 id / productId / code / sku 等）
const getProductRowKey = (row: any) => {
  return row?.id ?? row?.productId ?? row?.code ?? row?.sku ?? `${row?.name ?? ''}|${row?.spec ?? ''}`
}

// 查询产品列表（带分页）
const getProductList = async () => {
  try {
    // 在数据刷新期间屏蔽 selection-change 的增删逻辑，避免空选导致缓存被清
    restoringSelection.value = true
    const query = {
      pageNum: productPageNum.value,
      pageSize: productPageSize.value,
      categoryId: filters.value.categoryId || undefined,
      groupId: filters.value.groupId || undefined,
      name: filters.value.keyword || undefined
    }
    const res: any = await listMyProduct(query)
    productList.value = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : [])
    productTotal.value = Number(res?.total ?? 0)
    // 列表刷新后恢复已选行（使用跨页缓存 selectedProducts，适配筛选与分页）
    nextTick(() => {
      const selectedKeys = selectedProducts.value.map((p: any) => getProductRowKey(p)).filter(Boolean)
      console.log('跨页缓存已选商品KEY：', selectedKeys)
      const displayRows = filteredProducts.value
      const rowsToSelect = displayRows.filter((p: any) => selectedKeys.includes(getProductRowKey(p)))
      rowsToSelect.forEach((row: any) => {
        productTableRef.value?.toggleRowSelection?.(row, true)
      })
      restoringSelection.value = false
      console.log('跨页缓存已恢复选中商品：', rowsToSelect)
    })
  } catch (e) {
    productList.value = []
    productTotal.value = 0
    restoringSelection.value = false
  }
}

// 搜索过滤（改为直接使用后端分页数据，分类/分组走接口）
const filteredProducts = computed(() => {
  return productList.value
})
// 在筛选结果变化时，基于临时缓存回显当前页勾选
watch(filteredProducts, () => {
  if (!showProductDialog.value) return
  nextTick(() => {
    restoringSelection.value = true
    const selectedKeys = new Set(selectedProducts.value.map((p: any) => getProductRowKey(p)))
    const rowsToSelect = filteredProducts.value.filter((p: any) => selectedKeys.has(getProductRowKey(p)))
    rowsToSelect.forEach((row: any) => productTableRef.value?.toggleRowSelection?.(row, true))
    restoringSelection.value = false
  })
})

// 分页事件
const handleProductPageChange = (page: number) => {
  productPageNum.value = page
  getProductList()
}
const handleProductSizeChange = (size: number) => {
  productPageSize.value = size
  productPageNum.value = 1
  getProductList()
}


// 打印预览控制
const showPrintPreview = ref(false)
// 必填校验：客户/地址/模板/商品
const validateOrderSelections = (): boolean => {
  if (!selectedParty.value?.id) {
    ElMessage.error('请先选择客户/供应商');
    return false;
  }
  if (!form.value?.addressId) {
    ElMessage.error('请先选择发货地址');
    return false;
  }
  if (!selectedTemplate.value || !selectedTemplate.value?.templateId) {
    ElMessage.error('请先选择打印模板');
    return false;
  }
  if (!selectedProducts.value || selectedProducts.value.length === 0) {
    ElMessage.error('请先选择商品');
    return false;
  }
  return true;
}
const openPrintPreview = () => {
  if (!validateOrderSelections()) return;
  showPrintPreview.value = true
}



const handleSelectionChange = (rows) => {
  console.log('选中行：', rows)

  // 初次挂载或程序化回显时不处理，避免覆盖缓存
  if (restoringSelection.value) return

  const toKey = (x: any) => getProductRowKey(x)

  // 以 selectedProducts 作为“选中商品缓存列表”，按增量合并
  const cache = selectedProducts.value
  const cacheMap = new Map(cache.map((p: any) => [toKey(p), p]))

  // 1) 对选中返回的 rows：已存在则不动；不存在则添加到缓存（保留/默认价格与数量）
  rows.forEach((r: any) => {
    const k = toKey(r)
    if (!cacheMap.has(k)) {
      cache.push({
        ...r,
        price: (r.price ?? r.unitPrice ?? 0),
        quantity: (r.quantity ?? 1)
      })
      cacheMap.set(k, r)
    }
  })

  // 2) 对本页取消勾选的项：从缓存移除（不影响其他页已选）
  const visibleKeys = new Set(filteredProducts.value.map((r: any) => toKey(r)))
  const selectedKeysOnPage = new Set(rows.map((r: any) => toKey(r)))
  selectedProducts.value = cache.filter((p: any) => {
    const k = toKey(p)
    // 如果在当前页可见且不在本次选中集合中，视为取消勾选，移除
    return !(visibleKeys.has(k) && !selectedKeysOnPage.has(k))
  })
}

// 确认选择
const confirmSelection = () => {
  if (selectedProducts.value.length === 0) return
  // 将本次选中持久化，供下次打开弹窗恢复勾选
  persistedSelectedProducts.value = selectedProducts.value.map((p: any) => ({ ...p }))
  // emit('select-products', selectedProducts.value)
  showProductDialog.value = false
}

// 搜索操作
const searchProducts = () => {
  productPageNum.value = 1
  getProductList()
}


// 打印模板选择弹窗
const showTemplateDialog = ref(false)
// 模板列表
const templateList = ref([])
// 选中的模板
const selectedTemplate = ref(null)

// 选择模板
const selectTemplate = (item) => {
  selectedTemplate.value = item
}

// 确认选择模板
const confirmTemplate = () => {
  if (!selectedTemplate.value) return
  console.log('确认选择模板:', selectedTemplate.value)
  showTemplateDialog.value = false

}



const form = ref({
  customer: undefined,//客户名称
  address: undefined,
  productsCount: 0,
  templateId: undefined,
  orderType: "STATEMENT",
  orderNo: undefined,
  amount: 0,
  discountAmount: 0,
  actualAmount: 0,
  settleStatus: "PAID",
  voucherImgs: "https://loremflickr.com/400/400?lock=8401186471812490",
  signature: "测试签名",
  tagId: undefined,
  addressId: undefined,
  customerId: undefined,
  customerType: "SUPPLIER",
  remark: undefined,
  freight: 0,
  showFreight: false
})
// 添加默认值构造与重置方法
const getDefaultForm = () => ({
  customer: undefined,
  address: undefined,
  productsCount: 0,
  templateId: undefined,
  orderType: "STATEMENT",
  orderNo: undefined,
  amount: 0,
  discountAmount: 0,
  actualAmount: 0,
  settleStatus: "PAID",
  voucherImgs: "https://loremflickr.com/400/400?lock=8401186471812490",
  signature: "测试签名",
  tagId: undefined,
  addressId: undefined,
  customerId: undefined,
  customerType: "SUPPLIER",
  remark: undefined,
  freight: 0,
  showFreight: false
})
const resetOrderForm = () => {
  form.value = getDefaultForm()
  selectedProducts.value = []
  persistedSelectedProducts.value = []
  selectedTemplate.value = null
  selectedParty.value = { id: undefined, type: 'CUSTOMER', name: '', phone: '', address: '' }
  selectedAddressParty.value = {}
  filters.value = { categoryId: undefined, groupId: undefined, keyword: '' }
  productPageNum.value = 1
  productPageSize.value = 10
}

const today = new Date().toISOString().slice(0, 10)


// 映射结算状态枚举
const mapSettleStatus = (statusStr) => {
  const map = { UNPAID: 1, PARTIAL: 2, PAID: 3 }
  return map[statusStr] ?? 1
}



// 计算订单金额
const calcAmount = () => {
  return selectedProducts.value.reduce((sum, p) => {
    const price = (p.unitPrice ?? 0)
    const qty = (p.quantity ?? 1)
    return sum + price * qty
  }, 0)
}

const toChineseAmount = (num: number): string => {
  if (num === null || num === undefined || isNaN(Number(num))) return ''
  let amount = Math.round(Math.abs(Number(num)) * 100) // 两位小数转整数
  const negative = Number(num) < 0
  if (amount === 0) return '零元整'

  const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const radices = ['', '拾', '佰', '仟']
  const bigRadices = ['', '万', '亿', '兆']
  const decimals = ['角', '分']

  const integerStr = String(Math.floor(amount / 100))
  const decimalStr = String(amount % 100).padStart(2, '0')

  let chinese = ''

  // 整数部分
  if (parseInt(integerStr, 10) > 0) {
    const len = integerStr.length
    let zeroCount = 0
    for (let i = 0; i < len; i++) {
      const p = len - i - 1
      const d = parseInt(integerStr[i], 10)
      const quotient = Math.floor(p / 4)
      const modulus = p % 4
      if (d === 0) {
        zeroCount++
      } else {
        if (zeroCount > 0) chinese += '零'
        zeroCount = 0
        chinese += digits[d] + radices[modulus]
      }
      if (modulus === 0 && zeroCount < 4) chinese += bigRadices[quotient]
    }
    chinese += '元'
  } else {
    chinese += '零元'
  }

  // 小数部分
  const jiao = parseInt(decimalStr[0], 10)
  const fen = parseInt(decimalStr[1], 10)
  if (jiao === 0 && fen === 0) {
    chinese += '整'
  } else {
    if (jiao > 0) chinese += digits[jiao] + decimals[0]
    if (fen > 0) chinese += digits[fen] + decimals[1]
  }

  return negative ? ('负' + chinese) : chinese
}


const printTemplate = computed(() => {


  const buildTableRows = (items) => {
    let rowsHtml = ''
    for (let i = 0; i < items.length; i++) {

      const item = items[i]

      const price = (item.unitPrice || 0) * (item.quantity || 1);

      rowsHtml += `
      <tr>
        <td>${i + 1}</td>
        <td>${item.name || '-'}</td>
        <td>${item.spec || '-'}</td>
        <td>${item.unit || '-'}</td>
         <td>${item.quantity || 0}</td>
        <td>${item.unitPrice || 0}</td>
        <td>${price.toFixed(2)}</td>
      </tr>
    `
    }
    return rowsHtml
  }

  const buildEmptyRowsAlways7 = (baseLen) => {
    return Array.from({ length: baseLen > 6 ? 0 : 7 - baseLen }).map((_, i) => `
    <tr>
      <td>${baseLen + i + 1}</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  `).join('')
  }

  let inner = `<div id="printTemplate" class="print-template">
        
        <!-- 公司头部信息 -->
        <div class="company-header">
          <div class="company-name">
            <h1>${companyObject.value.company.name || '-'}</h1>
          </div>
          <div class="document-id">
            <p>NO: ${form.value.orderNo || '-'}</p>
          </div>
        </div>

        <div class="company-address">
          <p>地址: ${companyObject.value.company.province + companyObject.value.company.city + companyObject.value.company.district + companyObject.value.company.detailAddress || '-'}</p>
          <p>电话: ${companyObject.value.company.contact1 || '-'} ${companyObject.value.company.contact2 || '-'}</p>
        </div>

        <!-- 送货单标题 -->
        <div class="document-title">
          <h2>${form.value.orderTypeName || '-'}</h2>
        </div>

        <!-- 收货单位与日期 -->
        <div class="receiver-date">
          <div class="receiver">
            <span class="label">收货单位:</span>
            <span class="value">${form.value.customer || '-'}</span>
          </div>
          <div class="date-area">
            <span>${today}</span>
          </div>
        </div>

       <div class="receiver" style="margin-top:5px;">
            <span class="label">收货地址:</span>
            <span class="value">${selectedParty.value.address || '-'}</span>
        </div>
        
        <div style="display:flex;align-items:center;margin-top:5px;margin-bottom:10px;">
          <div class="receiver">
            <span class="label">联系人:</span>
            <span class="value">${selectedParty.value.contactPerson || '-'}</span>
          </div>
          <div class="receiver" style="margin-left:10px;">
            <span class="label">联系电话:</span>
            <span class="value">${selectedParty.value.phone || '-'}</span>
          </div>
        </div>
          

        <!-- 商品明细表格 -->
        <div class="items-table-print">
          <table>
            <thead>
              <tr>
                <th>序号</th>
                <th>货品名称</th>
                <th>规格</th>
                <th>单位</th>
                <th>数量</th>
                <th>单价</th>
                <th colspan="7">金额</th>
              </tr>
            </thead>
            <tbody>
              ${buildTableRows(selectedProducts.value)}
              ${buildEmptyRowsAlways7(selectedProducts.value.length)}
            </tbody>
          </table>
        </div>

        <!-- 底部备注与签字区 -->
        <div class="footer-section">
          <div class="note">
             <span class="total-value">总金额：${calcAmount().toFixed(2)}</span>
             ${form.value.showFreight ? `<span>运费（¥${ (form.value.freight || 0).toFixed(2)}）</span>` : ''}
          </div>
          <div class="chinese-amount">
            <span>大写金额：${toChineseAmount(calcAmount())}</span>
          </div>
           <div class="note">
            <span>注: ${form.value.remark || ''}</span>
          </div>
          <div class="signature-area">
            <div class="sender-signature">
              <p>送货单位及经手人（签字）：___________</p>
            </div>
            <div class="receiver-signature">
              <p>收货单位及经手人（签字）：___________</p>
            </div>
          </div>
        </div>
      </div>`;
  const printCss = `
  body{font-family:'SimSun',serif;font-size:14px;}
  .company-header{display:flex;align-items:center;justify-content:center;margin-bottom:10px;width:100%;position:relative;}
  .company-name h1{font-size:20px;margin:0;text-align:center;}
  .document-id{font-size:16px;font-weight:bold;position:absolute;top:0px;right:0px;}
  .company-address{text-align:center;margin-bottom:10px;line-height:1.5;}
  .document-title{text-align:center;margin-bottom:15px;}
  .document-title h2{font-size:24px;margin:0;}
  .receiver-date{display:flex;justify-content:space-between;}
  .receiver .label,.date-area{}
  .items-table-print table{width:100%;border-collapse:collapse;margin-bottom:15px;}
  .items-table-print th,.items-table-print td{border:1px solid #000;padding:5px;text-align:center;font-size:13px;}
  .items-table-print th{background-color:#f3f4f6;}
  .footer-section{margin-top:10px;line-height:1.8;}
  .note{display:flex;align-items:center;margin-bottom:10px;}
  .note .total-label{font-weight:bold;margin:0 5px;}
  .note .total-value{padding:2px 5px;}
  .chinese-amount{margin-bottom:5px;}
  .signature-area{display:flex;justify-content:space-between;}
  .sender-signature,.receiver-signature{width:45%;}
  `
  const html = `<!DOCTYPE html><html><head><meta charset="utf-8"/><style>${printCss}</style></head><body>${inner}</body></html>`

  return html;
});



const printDialogVisible = ref(false)
// 打印机列表
const printers = ref([])

// 选中的打印机
const selectedPrinter = ref('')
// 打印份数
const printCount = ref(1)



// 确认打印机
const confirmPrinter = async () => {
  if (!selectedPrinter.value) {
    ElMessage.warning('请选择打印机')
    return
  }

  // LODOP.PRINT_INITA(1,1,770,660,"送货单预览")
  LODOP.SET_PRINT_MODE("WINDOW_DEFPRINTER", selectedPrinter.value);
  LODOP.SET_PRINT_PAGESIZE(1, "241mm", "187mm", "")
  LODOP.ADD_PRINT_HTM(1, 1, "100%", "100%", printTemplate.value)
  LODOP.SET_PRINT_COPIES(printCount.value)
  LODOP.PRINT()
  // LODOP.PREVIEW();
  // 计算金额
  const amount = calcAmount()
  const discountAmount = 0
  const actualAmount = amount - discountAmount
  form.value.total = amount

  // 构造请求参数
  const payload = {
    templateId: selectedTemplate.value?.templateId,
    orderType: form.value.orderType,
    orderTypeName: form.value.orderTypeName,
    amount,
    discountAmount,
    actualAmount,
    settleStatus: mapSettleStatus('PAID'),
    voucherImgs: '',
    signature: '',
    tagId: undefined,
    addressId: form.value?.addressId,
    customerId: selectedParty.value.id,
    customerType: selectedParty.value.type,
    customerName: selectedParty.value.name,
    customerPhone: selectedParty.value.phone,
    customerAddress: selectedParty.value.address,
    freightAmount: form.value.showFreight ? (form.value.freight || 0) : 0,
    orderProductList: selectedProducts.value.map(p => ({
      productId: p.id ?? p.productId,
      quantity: p.quantity ?? 1,
      unitPrice: p.price ?? p.unitPrice ?? 0
    })),
    remark: form.value.remark || ''
  }

  try {
    await myAddOrder(payload)
    ElMessage.success('订单已保存')
    showDialog.value = false
    console.log('保存并打印 payload:', payload)
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('myAddOrder error:', error)
  }
  printDialogVisible.value = false


}

// 保存订单
const saveOrder = async () => {    
    // 必填项校验
  if (!validateOrderSelections()) return;

   const amount = calcAmount()
  const discountAmount = 0
  const actualAmount = amount - discountAmount
  form.value.total = amount

  // 构造请求参数
  const payload = {
    templateId: selectedTemplate.value?.templateId,
    orderType: form.value.orderType,
    orderTypeName: form.value.orderTypeName,
    amount,
    discountAmount,
    actualAmount,
    settleStatus: mapSettleStatus('PAID'),
    voucherImgs: '',
    signature: '',
    tagId: undefined,
    addressId: form.value?.addressId,
    customerId: selectedParty.value.id,
    customerType: selectedParty.value.type,
    customerName: selectedParty.value.name,
    customerPhone: selectedParty.value.phone,
    customerAddress: selectedParty.value.address,
    freightAmount: form.value.showFreight ? (form.value.freight || 0) : 0,
    orderProductList: selectedProducts.value.map(p => ({
      productId: p.id ?? p.productId,
      quantity: p.quantity ?? 1,
      unitPrice: p.price ?? p.unitPrice ?? 0
    })),
    remark: form.value.remark || ''
  }

  try {
    await myAddOrder(payload)
    ElMessage.success('订单已保存')
    showDialog.value = false
    resetOrderForm()
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('myAddOrder error:', error)
  }
}


const saveAndPrint = async () => {    
    // 必填项校验
  if (!validateOrderSelections()) return;

  printDialogVisible.value = true

  const printer = [];
  for (let i = 0; i < LODOP.GET_PRINTER_COUNT(); i++) {
    printer.push(LODOP.GET_PRINTER_NAME(i));
  }

  printers.value = printer;

  selectedPrinter.value = "EPSON LQ-635K ESC/P2"

  console.log('打印机列表:', printer)
}

// 快捷开单默认图标
const quickList = ref([
  { name: '发货单', icon: icon1 , orderType: 'DELIVERY' },
   { name: '采购单', icon: icon5 , orderType: 'PROCUREMENT' },
  { name: '缴费单', icon: icon2 , orderType: 'PURCHASE' },
  { name: '报价单', icon: icon3 , orderType: 'QUOTATION' },
  { name: '销售单', icon: icon4, orderType: 'SALES' },
  { name: '工资单', icon: icon6 , orderType: 'STATEMENT' },
  { name: '退货单', icon: icon7 , orderType: 'RETURN' },
])


// 删除产品（同步移除弹窗勾选与持久集合）
const removeProduct = (index) => {
  const removed = selectedProducts.value[index]
  if (!removed) return
  const key = getProductRowKey(removed)
  // 移除主列表
  selectedProducts.value.splice(index, 1)
  // 同步持久化选择集合，避免下次打开又被恢复
  persistedSelectedProducts.value = persistedSelectedProducts.value.filter((p: any) => getProductRowKey(p) !== key)
  // 若弹窗已打开且当前显示列表包含该商品，则取消勾选（适配筛选与分页）
  const row = filteredProducts.value.find((r: any) => getProductRowKey(r) === key)
  if (row && productTableRef.value?.toggleRowSelection) {
    productTableRef.value.toggleRowSelection(row, false)
  }
}

// 客户列表
const customerList = ref([])

// 供应商列表
const supplierList = ref([])

const selectedParty = ref({ id: undefined, type: 'CUSTOMER', name: '', phone: '', address: '' })
// 组装地址字符串（兼容客户/供应商与地址VO字段）
const assembleAddress = (row) => {
  const parts = [row?.province, row?.city, (row?.district ?? row?.area), (row?.detailAddress ?? row?.address)].filter(Boolean)
  return parts.length ? parts.join('') : ''
}

// 选择客户弹窗点击事件
const showCustomerDialogClick = () => {
  showCustomerDialog.value = true
  myCustomerList().then(res => {
    console.log('客户列表:', res)
    customerList.value = res.rows || []
  })
}

// 打开发货地址弹窗并加载地址列表
const openAddressDialog = () => {
  showAddressDialog.value = true
  myListAddress().then(res => {
    addressList.value = res.rows || []
  })
}

// 选择商品弹窗点击事件
const showProductDialogClick = () => {
  showProductDialog.value = true
  // 打开时先用持久化集合回填临时选中集合，随后刷新列表并恢复勾选
  selectedProducts.value = persistedSelectedProducts.value.map((p: any) => ({ ...p }))
  getProductList()

  getCategoryList();

  getProductGroupList();
}





const quickOrderClick = (item) => {
  console.log(item)
  selectedTemplate.value = item
  showDialog.value = true
  form.value.orderType = item.orderType
  form.value.orderTypeName = item.name  

  getOrderNo().then(res => {
    form.value.orderNo = res.data|| ''
  })
  

   myCollectTemplateList().then(res => {
    console.log('收藏模板列表:', res)
    templateList.value = res.rows || []
    // 打开弹窗后默认选择第一项（列表为空则不选）
    if (Array.isArray(templateList.value) && templateList.value.length > 0) {
      selectedTemplate.value = templateList.value[0]
      console.log('默认选择模板:', selectedTemplate.value)
    } else {
      selectedTemplate.value = null
    }
  })

}


// 选择打印模板弹窗点击事件
const showTemplateDialogClick = () => {
  showTemplateDialog.value = true
  myCollectTemplateList().then(res => {
    console.log('收藏模板列表:', res)
    templateList.value = res.rows || []
    // 打开弹窗后默认选择第一项（列表为空则不选）
    if (Array.isArray(templateList.value) && templateList.value.length > 0) {
      selectedTemplate.value = templateList.value[0]
      console.log('默认选择模板:', selectedTemplate.value)
    } else {
      selectedTemplate.value = null
    }
  })
}

const companyObject = ref({});

const orderSummary = ref({})

onMounted(async () => {
  // 先检查是否已补全公司信息
  try {
    const res = await checkCompany()
    if (res.code !== 200) {
      // 预填充已有公司信息
       forceCompanyDialogVisible.value = true
      try {
        prefillCompleteCompanyForm({})
      } catch (e) {}
     
    }
  } catch (e) {
      forceCompanyDialogVisible.value = true
       prefillCompleteCompanyForm({})
  }
  // 加载公司详情与首页统计
  getCompanyDetail().then(res => {
    companyObject.value = res.data
  })
  getOrderSummary({}).then(res => {
    orderSummary.value = res.data || {}
  })
})

</script>

<style scoped>
.home-page {
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.delivery-dialog {
  .el-dialog__header {
    border-bottom: 1px solid #f0f0f0;
  }
}

.delivery-form {
  margin-top: 10px;
}

.card-header {
  font-weight: 600;
  font-size: 15px;
  color: #333;
}

.info-card p {
  margin: 6px 0;
  color: #555;
}

.sign-card,
.info-card {
  margin-top: 20px;
  border-radius: 10px;
  background: #fafafa;
}

.template-list {
  padding: 10px 0;
}

.template-card {
  background: #fff;
  border: 2px solid transparent;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  cursor: pointer;
  transition: all 0.2s;
}

.template-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.template-card.active {
  border-color: #409eff;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.3);
}

.template-img {
  width: 100%;
  height: 150px;
  object-fit: cover;
  background-color: #f6f6f6;
}

.template-info {
  padding: 10px;
  text-align: center;
}

.template-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.template-desc {
  font-size: 12px;
  color: #888;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.gap-3 {
  gap: 12px;
}

.mb-4 {
  margin-bottom: 16px;
}

.cursor-pointer {
  cursor: pointer;
}
</style>